# -*- coding: iso-8859-15 -*-
from Bio.Alphabet import generic_dna
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align import MultipleSeqAlignment
from Bio import AlignIO
from Bio.Align.Applications import MuscleCommandline
from globals import *

sequences = {}

def GetSequenceFromUser(counter):
    user_input = raw_input(str(counter) + '.  ')

    if user_input == '':
        return False
    else:
        sequence, id = user_input.split(' ')
        sequences[id] = sequence
        return True

# def GenerateMultipleSeqAlignmentFromSequence():
#     tempTable = []
#
#     for id, sequence in sequences.iteritems():
#         print id, sequence
#         tempTable.append(SeqRecord(Seq(sequence, generic_dna), id=id))
#
#     return MultipleSeqAlignment(tempTable)

def GetSequencesFromUser():
    print ''
    print 'Wprowadź kolejne sekwencje oraz ich identyfikatory.'
    print 'Sekwencja i identyfikator powinny być oddzielone spacją.'
    print 'Pusta linia potrakwowana zostanie jako zakończenie wprowadzania sekwencji.'

    counter = 1
    isEndOfSequences = True

    while isEndOfSequences:
        isEndOfSequences = GetSequenceFromUser(counter)
        counter += 1

    return counter-2

def SaveSequencesToTempFile():
    with open(temp_before_aligment, 'wb') as writer:
        for id, sequence in sequences.iteritems():
            writer.write('>' + id)
            writer.write('\n' + sequence+'\n')


def RunMuscleForSequenceAligment():

    muscle_cline = MuscleCommandline(muscle_exe, input=temp_before_aligment, out=temp_after_aligment)
    stdout, stderr = muscle_cline()

def ShowMultiSequenceAligment(sequenceCount):
    for alignment in AlignIO.parse(temp_after_aligment, "fasta", seq_count=sequenceCount):
        print("Alignment length %i" % alignment.get_alignment_length())
        for record in alignment:
            print("%s - %s" % (record.seq, record.id))
        print("")


def Run():
    sequences = {}
    sequenceCount = GetSequencesFromUser()
    SaveSequencesToTempFile()
    RunMuscleForSequenceAligment()
    ShowMultiSequenceAligment(sequenceCount)
    # align = GenerateMultipleSeqAlignmentFromSequence()
    # AlignIO.write(align, "temp.phy", "phylip")

